package com.property.demo.service.impl;

import com.property.demo.model.Home;
import com.property.demo.model.Owner;
import com.property.demo.repository.HomeRepository;
import com.property.demo.repository.OwnerRepository;
import com.property.demo.service.OwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class OwnerServiceImpl implements OwnerService {

    @Autowired
    private OwnerRepository ownerRepository;
    
    @Autowired
    private HomeRepository homeRepository;

    @Override
    public List<Owner> findAll() {
        return ownerRepository.findAll();
    }

    @Override
    public Page<Owner> findAll(Pageable pageable) {
        return ownerRepository.findAll(pageable);
    }

    @Override
    public Optional<Owner> findById(Long id) {
        return ownerRepository.findById(id);
    }

    @Override
    public Owner save(Owner owner) {
        owner.setCreatedAt(new Date());
        owner.setUpdatedAt(new Date());
        return ownerRepository.save(owner);
    }

    @Override
    public Owner update(Long id, Owner ownerDetails) {
        return ownerRepository.findById(id)
                .map(owner -> {
                    owner.setName(ownerDetails.getName());
                    owner.setGender(ownerDetails.getGender());
                    owner.setPhoneNumber(ownerDetails.getPhoneNumber());
                    owner.setIdCard(ownerDetails.getIdCard());
                    owner.setProfession(ownerDetails.getProfession());
                    owner.setEmail(ownerDetails.getEmail());
                    owner.setRemarks(ownerDetails.getRemarks());
                    owner.setUpdatedAt(new Date());
                    return ownerRepository.save(owner);
                })
                .orElse(null);
    }

    @Override
    public void delete(Long id) {
        ownerRepository.deleteById(id);
    }

    @Override
    public void deleteAll(List<Long> ids) {
        for (Long id : ids) {
            ownerRepository.deleteById(id);
        }
    }

    @Override
    public List<Owner> findByName(String name) {
        return ownerRepository.findByNameContaining(name);
    }

    @Override
    public List<Owner> findByPhoneNumber(String phoneNumber) {
        return ownerRepository.findByPhoneNumber(phoneNumber);
    }

    @Override
    public List<Owner> findByIdCard(String idCard) {
        // 使用Optional<Owner>转换为List<Owner>
        Optional<Owner> ownerOpt = ownerRepository.findByIdCard(idCard);
        return ownerOpt.isPresent() ? Collections.singletonList(ownerOpt.get()) : Collections.emptyList();
    }
    
    @Override
    public Page<Owner> findByFilters(String name, String phoneNumber, String idCard, Pageable pageable) {
        if (name != null && !name.isEmpty()) {
            // 由于OwnerRepository没有提供带Pageable的findByNameContaining方法，
            // 这里只能先获取所有符合条件的数据，然后手动分页
            List<Owner> owners = ownerRepository.findByNameContaining(name);
            return convertListToPage(owners, pageable);
        } else if (phoneNumber != null && !phoneNumber.isEmpty()) {
            List<Owner> owners = ownerRepository.findByPhoneNumber(phoneNumber);
            return convertListToPage(owners, pageable);
        } else if (idCard != null && !idCard.isEmpty()) {
            Optional<Owner> ownerOpt = ownerRepository.findByIdCard(idCard);
            List<Owner> owners = ownerOpt.isPresent() ? 
                    Collections.singletonList(ownerOpt.get()) : 
                    Collections.emptyList();
            return convertListToPage(owners, pageable);
        } else {
            return ownerRepository.findAll(pageable);
        }
    }
    
    // 将List<Owner>转换为Page<Owner>的辅助方法
    private Page<Owner> convertListToPage(List<Owner> list, Pageable pageable) {
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), list.size());
        
        if (start > list.size()) {
            start = 0;
            end = 0;
        }
        
        List<Owner> subList = start < end ? list.subList(start, end) : Collections.emptyList();
        
        return new PageImpl<>(subList, pageable, list.size());
    }
    
    /**
     * 根据业主ID获取所属小区名称
     * @param ownerId 业主ID
     * @return 小区名称，如果没有找到则返回null
     */
    @Override
    public String findCommunityNameByOwnerId(Long ownerId) {
        // 通过房屋关系查找小区
        List<Home> homes = homeRepository.findByOwnerId(ownerId);
        
        // 如果业主有房屋，从第一个房屋获取小区信息
        if (homes != null && !homes.isEmpty()) {
            Home home = homes.get(0);
            if (home.getBuilding() != null && home.getBuilding().getCommunity() != null) {
                return home.getBuilding().getCommunity().getName();
            }
        }
        
        return null;
    }
} 